package com.xuhai.blog19.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhai.blog19.admin.dao.ArticleCategoryDao;
import com.xuhai.blog19.admin.dao.CategoryDao;
import com.xuhai.blog19.admin.entity.CategoryEntity;
import com.xuhai.blog19.admin.service.CategoryService;
import com.xuhai.blog19.common.exception.RTException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author PangJunjie
 * @Date 2023/2/8/008
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private ArticleCategoryDao articleCategoryDao;
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public IPage<CategoryEntity> getPage(int page, int limit, CategoryEntity category) {
        return this.page(new Page<>(page, limit), new QueryWrapper<CategoryEntity>().eq(StringUtils.isNotBlank(category.getCategoryName()), "category_name", category.getCategoryName()).eq(category.getStatus() != null, "status", category.getStatus()).orderByDesc("category_id"));
    }

    @Override
    public List<CategoryEntity> getSelect() {
        return this.list(new QueryWrapper<CategoryEntity>().eq("status", 1));
    }

    @Override
    public void delete(int categoryId) {
        if (articleCategoryDao.getArticleByCategoryId(categoryId).size() == 0) {
            this.removeById(categoryId);
        } else {
            throw new RTException("该分类已被使用，禁止删除！");
        }
    }

    @Override
    public int getCount(Integer status) {
        return this.count(new QueryWrapper<CategoryEntity>().eq(status != null, "status", status));
    }

    @Override
    public List<CategoryEntity> getCategoryArticleCount() {
        return categoryDao.getCategoryArticleCount();
    }
}
